package org.fly.service.impl;

import org.fly.bean.*;
import org.fly.bean.query.CartQuery;
import org.fly.bean.query.CustomerLevelQuery;
import org.fly.bean.query.SCLRQuery;
import org.fly.bean.query.SupplierProductQuery;
import org.fly.bean.warpper.CartGroupWarpper;
import org.fly.bean.warpper.CartWarpper;
import org.fly.dao.*;
import org.fly.service.CartService;
import org.fly.utils.CustomerLevelUtils;
import org.fly.utils.PriceUtils;
import org.fly.utils.StringNumber;
import org.fly.utils.UUIDFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.fly.bean.common.BusinessException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Created by autoCode on 2018-04-08 15:31:55.
*/
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartDao cartDao;
    @Autowired
    ProductDao productDao;
    @Autowired
    SupplierDao supplierDao;
    @Autowired
    SupplierProductDao supplierProductDao;
    @Autowired
    CustomerLevelDao customerLevelDao;
    @Autowired
    SCLRDao  sclrDao;
    @Autowired
    ProductNormDao productNormDao;

    @Override
    public List<Cart> list(CartQuery query) {
        return cartDao.list(query);
    }

    @Override
    public long count(CartQuery query) {
        return cartDao.count(query);
    }

    @Override
    public Cart findById(String id) {
        return cartDao.findById(id);
    }

    @Override
    public void save(Cart bean)  throws BusinessException {

    if(StringUtils.isNotBlank(bean.getId())){
         Cart cartDb = cartDao.findById(bean.getId());
         cartDb.setNum(bean.getNum());
         cartDao.update(cartDb);
    }else {
        bean.setId(UUIDFactory.random());
        bean.setCreateTime(System.currentTimeMillis());
        cartDao.insert(bean);
    }
    }

    @Override
    public void delete(String id) {
        cartDao.delete(id);
    }

    @Override
    public Page queryPage(CartQuery query) {
        String customerId =  query.getCustomerId();
        List<Cart>  carts =  cartDao.list(query);
        List<CartWarpper> list  = new ArrayList<>();
        long count =  cartDao.count(query);
        List<String> supplierIdList  = new ArrayList<>();
        List<String> productIdList = new ArrayList<>();
        if(!carts.isEmpty()){
            carts.forEach(e->{
                if(!supplierIdList.contains(e.getSupplierId())){
                    supplierIdList.add(e.getSupplierId()) ;
                }
                if(!productIdList.contains(e.getProductId())){
                    productIdList.add(e.getProductId());
                }
            });
            list =  convertCartWarpperList(carts,supplierIdList,productIdList,customerId);

        }

        Page page = new Page(query.getPage(),query.getSize());
        page.setData(list);
        page.setTotal(count);
        return page;
    }

    @Override
    public Page queryGroupPage(CartQuery query) {
        List<CartGroupWarpper> cartGroupWarppers =  cartDao.listCartGroup(query);
        String customerId = query.getCustomerId();
        long count =  cartDao.countCartGroup(query);
        List<String> supplierIdList = new ArrayList<>();
        List<String> productIdList  = new ArrayList<>();
        cartGroupWarppers.forEach(e->{
            if(!supplierIdList.contains(e.getSupplierId())){
                supplierIdList.add(e.getSupplierId());
            }
        });
        List<Cart> carts = cartDao.listBySupplierIds(supplierIdList);

        carts.forEach(e->{
            if(!productIdList.contains(e.getProductId())){
                productIdList.add(e.getProductId());
            }
        });

        List<CartWarpper> list = convertCartWarpperList(carts,supplierIdList,productIdList,customerId);
        Map<String,List<CartWarpper>> cartWarpperMap = list.stream().
                collect(Collectors.groupingBy(e->e.getSupplierId(),Collectors.toList()));
        cartGroupWarppers.forEach(e->{
            List<CartWarpper> cartWarppers = cartWarpperMap.get(e.getSupplierId());
            e.setCartWarpperList(cartWarppers);
            e.setSupplier(cartWarppers.get(0).getSupplier());
        });

        Page page = new Page(query.getPage(),query.getSize());
        page.setData(cartGroupWarppers);
        page.setTotal(count);
        return page;
    }

    private  List<CartWarpper> convertCartWarpperList(List<Cart> carts,
                                                      List<String> supplierIdList,
                                                      List<String> productIdList,
                                                      String customerId){
        List<CartWarpper> list;
        List<Product> products =  productDao.listByIds(productIdList);
        List<Supplier> suppliers =  supplierDao.listByIds(supplierIdList);

        SupplierProductQuery supplierProductQuery = new SupplierProductQuery();
        supplierProductQuery.setProductIdList(productIdList);
        supplierProductQuery.setSupplierIdList(supplierIdList);
        List<SupplierProduct>  supplierProductList  = supplierProductDao.list(supplierProductQuery);
        Map<String,SupplierProduct> spMap = supplierProductList.stream().
                collect(Collectors.toMap(e->e.getSupplierId()+"_"+e.getProductId(),e->e));

        Map<String,Product> productMap = products.stream().collect(Collectors.toMap(e->e.getId(), e->e));
        Map<String,Supplier> supplierMap = suppliers.stream().collect(Collectors.toMap(e->e.getId(),e->e));

        //获取 用于计算客户级别的数据
        CustomerLevelQuery customerLevelQuery = new CustomerLevelQuery();
        customerLevelQuery.setSupplierIdList(supplierIdList);
        List<CustomerLevel> customerLevels = customerLevelDao.list(customerLevelQuery);
        //供货商默认的级别map
        Map<String,CustomerLevel> customerLevelMap = customerLevels.stream().filter(e->e.getDefaultSet()  ==1 ).
                collect(Collectors.toMap(e->e.getSupplierId(), e->e));

        SCLRQuery sclrQuery = new SCLRQuery();
        sclrQuery.setSupplierIdList(supplierIdList);
        sclrQuery.setCustomerId(customerId);
        List<SCLR>  sclrs  = sclrDao.list(sclrQuery);
        Map<String,SCLR> sclrMap = sclrs.stream().collect(Collectors.toMap(e->e.getSupplierId(),e->e));
        //获取商品规格信息
        List<ProductNorm> productNormList = productNormDao.listByProductIds(productIdList);
        Map<String,ProductNorm> pnMap  = productNormList.stream().collect(Collectors.toMap(e->e.getProductId(),e->e));


        list = carts.stream().map(e->{
            CartWarpper warpper = new CartWarpper();
            Product product = productMap.get(e.getProductId());
            Supplier supplier = supplierMap.get(e.getSupplierId());
            ProductNorm productNorm = pnMap.get(e.getProductId());
            String customerLevel = CustomerLevelUtils.
                    getCustomerLevel(customerId,e.getSupplierId(),customerLevelMap,sclrMap);
            warpper.setProduct(product);
            warpper.setSupplier(supplier);
            SupplierProduct supplierProduct = spMap.get(e.getSupplierId()+"_"+e.getProductId());
            String singlePrice = PriceUtils.calcPrice(supplierProduct,customerLevel,
                    productNorm,e.getNorm()
            );
            warpper.setPrice(singlePrice);
            String  money = StringNumber.mul(singlePrice,String.valueOf(e.getNum()));
            warpper.setMoney(money);
            BeanUtils.copyProperties(e,warpper);
            return  warpper;
        }).collect(Collectors.toList());
        return list;
    }
}
